﻿using Microsoft.International.Converters.PinYinConverter;
using System.Runtime.CompilerServices;
using System.Security.Cryptography;
using System.Text;
using Volo.Abp;

namespace CTP.CRM.Core.Helper
{
    /// <summary>
    /// 常用帮助类
    /// </summary>
    public class UserCenterHelper
    {

        private static Random _random = new Random();
        /// <summary>
        /// 汉字转化为拼音首字母
        /// </summary>
        /// <param name="str">汉字</param>
        /// <returns>首字母</returns>
        public static string GetHanziToFirstPinyin(string str)
        {
            string r = string.Empty;
            foreach (char obj in str)
            {
                try
                {
                    ChineseChar chineseChar = new ChineseChar(obj);
                    string t = chineseChar.Pinyins[0].ToString();
                    r += t.Substring(0, 1);
                }
                catch
                {
                    r += obj.ToString();
                }
            }
            return r;
        }

        /// <summary>
        /// 汉字转化为拼音
        /// </summary>
        /// <param name="str">汉字</param>
        /// <returns>全拼</returns>
        public static string GetHanziToPinyin(string str)
        {
            string r = string.Empty;
            foreach (char obj in str)
            {
                try
                {
                    ChineseChar chineseChar = new ChineseChar(obj);
                    string t = chineseChar.Pinyins[0].ToString();
                    r += t.Substring(0, t.Length - 1);
                }
                catch
                {
                    r += obj.ToString();
                }
            }
            return r;
        }

        /// <summary>
        /// 生成时间戳
        /// </summary>
        /// <returns></returns>
        public static string GenerateTimestamp() => new DateTimeOffset(DateTime.UtcNow).ToUnixTimeSeconds().ToString();

        /// <summary>
        /// 生成时间戳，毫秒
        /// </summary>
        /// <returns></returns>
        public static string GenerateTimestampMillion() => new DateTimeOffset(DateTime.UtcNow).ToUnixTimeMilliseconds().ToString();

        /// <summary>
        /// sha1加密
        /// </summary>
        /// <param name="str"></param>
        /// <returns></returns>
        public static string GetSha1(string str)
        {
            var buffer = Encoding.UTF8.GetBytes(str);
            var data = SHA1.Create().ComputeHash(buffer);
            string result = BitConverter.ToString(data).Replace("-", string.Empty).ToLower();
            return result;
        }

        /// <summary>
        /// 判断集合是否为null或空集合
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="ListT"></param>
        /// <returns></returns>
        public static bool CheckListIsNoneOrNull<T>(List<T> ListT) => ListT == null || !ListT.Any();

        /// <summary>
        /// 去除字符串空格
        /// </summary>
        /// <param name="val"></param>
        /// <returns></returns>
        public static string RemoveStringSpace(string val) => val.IsNullOrWhiteSpace() ? val : val.Trim();

        /// <summary>
        /// 签名调用飞书中台参数
        /// </summary>
        /// <param name="memberName"></param>
        /// <returns></returns>
        /// <exception cref="BusinessException"></exception>
        public static (string, string) SignatureInvokeFsCenterParams([CallerMemberName] string memberName = "")
        {
            var appId = CTPABPCore.Configuration["BrowserFsSignin:Appid"];
            var secretKey = CTPABPCore.Configuration["BrowserFsSignin:AppSecret"];
            if (string.IsNullOrEmpty(appId) || string.IsNullOrEmpty(secretKey)) throw new BusinessException($"{memberName} 读取飞书配置异常，请联系管理员!");

            string signAfter = string.Empty;
            try
            {
                //调用加密可能异常
                RSAContext.Encrypt(Encoding.UTF8.GetBytes(secretKey), out var signbytes);
                signAfter = Convert.ToBase64String(signbytes);
            }
            catch (Exception)
            {
                throw new BusinessException($"{memberName} 飞书参数加密异常，请联系管理员!");
            }
            return (appId, signAfter);
        }

        /// <summary>
        /// 按照给定长度给集合分组
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="sources">源集合</param>
        /// <param name="capacity">一组多少个</param>
        /// <returns></returns>
        public static List<List<T>> SplitElementGroupOfList<T>(IList<T> sources, int capacity)
        {
            List<T> templist = null;
            List<List<T>> relist = new List<List<T>>();
            for (int i = 0; i < (sources.Count % capacity == 0 ? sources.Count / capacity : sources.Count / capacity + 1); i++)
            {
                templist = new List<T>();
                for (int j = 0; j < capacity; j++)
                {
                    int index = i * capacity + j;
                    if (index == sources.Count) { break; }
                    templist.Add(sources[index]);
                }
                relist.Add(templist);
            }
            return relist;
        }

        /// <summary>
        /// 验证json字符串是否合法
        /// </summary>
        /// <param name="str"></param>
        /// <returns></returns>
        public static bool IsJson(string str)
        {
            try
            {
                Newtonsoft.Json.JsonConvert.DeserializeObject(str);
            }
            catch (Exception)
            {
                return false;
            }
            return true;
        }

        /// <summary>
        /// 获取当前时间时间戳
        /// </summary>
        /// <returns></returns>
        public static string GetTimeSpan()
        {
            var timespan = new DateTimeOffset(DateTime.UtcNow).ToUnixTimeSeconds();
            return timespan.ToString();
        }

        /// <summary>
        /// 时间戳转时间
        /// </summary>
        /// <param name="unixTime"></param>
        /// <returns></returns>
        public static DateTime FromUnixTimestamp(long unixTime)
        {
            return TimeZoneInfo.ConvertTime(new DateTime(1970, 1, 1), TimeZoneInfo.Utc, TimeZoneInfo.Local).AddMilliseconds(unixTime);
        }

        /// <summary>
        /// 获取字符串的hash值
        /// </summary>
        /// <param name="str"></param>
        /// <returns></returns>
        public static string CalculateStringHash(string str)
        {
            var sha256 = SHA256.Create();
            var hashBytes = sha256.ComputeHash(Encoding.UTF8.GetBytes(str));
            var sb = new StringBuilder();
            foreach (var t in hashBytes)
            {
                sb.Append(t.ToString("x2"));
            }
            return sb.ToString();
        }

        /// <summary>
        /// 生成一个随机字符串
        /// </summary>
        /// <returns></returns>
        public static string GenerateRandomMixedCaseString()
        {
            const int length = 28;
            const string chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
            StringBuilder sb = new StringBuilder(length);
            for (var i = 0; i < length; i++)
            {
                var index = _random.Next(chars.Length);
                sb.Append(chars[index]);
            }
            return sb.ToString();
        }
    }
}
